module.exports = ['$timeout',
    function ($timeout) {
        return {
            restrict  : 'E',
            scope     : {
                ngModel: '='
            },
            require   : 'ngModel',
            template  : '<div style="display: inline"></div>',
            replace   : true,
            transclude: true,
            compile   : function (el, attrs, transcludeFn) {
                return function (scope, element, attrs, ngModel) {
                    transcludeFn(scope, function (clone) {
                        var models = {};
                        var checks = clone.find('input[type=checkbox]');
                        //console.log('ngModelCtrl', ngModel);

                        scope.$watch('ngModel', function (val, old) {
                            //console.log('captured watch', val, old);
                            (val || "")
                                .split(',')
                                .filter(function (a) {
                                    return a != ""
                                })
                                .forEach(function (e) {
                                    models[e] = true;
                                });

                            angular.forEach(checks, function (input) {
                                //console.log(input);
                                input.checked = models[input.name];
                            });
                        });


                        //console.log('model', models);

                        //console.log('checkboxes',checks);
                        angular.forEach(checks, function (input) {
                            // console.log(input);
                            input.checked = models[input.name];
                            $(input).on('change', function (e) {
                                //console.log('change', this.name, this.checked);
                                on_change(this.name, this.checked);
                            });
                        });
                        el.append(clone);
                        //console.log(scope);

                        function on_change(name, checked) {
                            models[name] = checked;
                            ngModel.$setViewValue(build_string());
                        }

                        function build_string() {
                            return Object.keys(models)
                                .filter(function (a) {
                                    return a && a != "" && models[a]
                                })
                                .reduce(function (accum, cur, index, array) {
                                    return index != (array.length - 1) ? (accum + cur + ',') : (accum + cur);
                                }, "");
                        }
                    })
                }
            }
        }
    }];
